﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace QLevelGenerator.Infrastructure
{
    public class TwoDimensionalArrayBinder<T> : IModelBinder
    {
        public object BindModel(System.Web.Mvc.ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string key = bindingContext.ModelName;
            try
            {
                int totalRows = 0;
                var javascriptObject = bindingContext.ValueProvider.GetValue(key);
                if (javascriptObject != null)
                {
                    var arrays = (javascriptObject.RawValue as string[])[0].Split(';');
                    var list = new List<int[]>();
                    foreach(var array in arrays)
                    {
                        if (string.IsNullOrEmpty(array))
                        {
                            continue;
                        }

                        var intArray = array.Trim(';')
                            .Replace('[', ' ')
                            .Replace(']',' ')
                            .Split(',')
                            .Select(val => int.Parse(val)).ToArray();
                        list.Add(intArray);
                    }
                    var result = list.ToArray();
                    bindingContext.ModelState.SetModelValue(key, new ValueProviderResult(result, string.Empty, CultureInfo.InvariantCulture));
                    return result;
                }
            }
            catch
            {
                bindingContext.ModelState.AddModelError(key, "Data is not in correct Format");
            }
            return null;
        }

    }
}